/**
 * electron 主文件
 */
// import { join } from 'path'
import { app, BrowserWindow, ipcMain } from 'electron'
import is_dev from 'electron-is-dev'
import dotenv from 'dotenv'
import Store from 'electron-store'
import { OpenDialog } from "./api/OpenDialog";
import { initWinEvent } from "./api/window";
import { join } from 'path'

const store = new Store()
ipcMain.on('store:set', async (e, args) => {
  store.set(args.key, args.value)
})
ipcMain.handle('store:get', async (e, args) => {
  const value = await store.get(args)
  return value
})

ipcMain.on('store:delete', async (e, args) => {
  store.delete(args)
})

dotenv.config({ path: join(__dirname, '../../.env') })

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    height: 900,
    width: 1200,
    // fullscreen: true,
    frame: false,
    webPreferences: {
      // enableRemoteModule: true,
      // 为了在渲染进程使用node环境, 这两个选项都要加上
      nodeIntegration: true,
      contextIsolation: false
    },
  })

  const indexHtmlUrl = is_dev
    ? `http://localhost:${process.env.PORT}` // vite 启动的服务器地址
    : `file://${join(__dirname, '../../dist/render/index.html')}` // vite 构建后的静态文件地址

  mainWindow.loadURL(indexHtmlUrl)

  // if (process.env.NODE_ENV === 'development') {

  // }

  // mainWindow.webContents.on('did-frame-finish-load', () => {
  //   mainWindow.webContents.once('devtools-opened', () => {
  //     mainWindow.focus()
  //   })
  //   mainWindow.webContents.openDevTools()
  // })

  // 限制只可以打开一个应用
  const gotTheLock = app.requestSingleInstanceLock()
  if (!gotTheLock) {
    app.quit()
  } else {
    app.on('second-instance', (event, commandLine, workingDirectory) => {
      // 当运行第二个实例时,将会聚焦到mainWindow这个窗口
      if (mainWindow) {
        if (mainWindow.isMinimized()) mainWindow.restore()
        mainWindow.focus()
        mainWindow.show()
      }
    })
  }

  // 隐藏菜单栏
  // mainWindow.setMenu(null)

  // 最大化
  // mainWindow.maximize()

  // 打开文件
  const openDialog = new OpenDialog();
  openDialog.init()
  initWinEvent(mainWindow);

  // webServer();

  return mainWindow
}

app.whenReady().then(() => createWindow())


app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

app.on('browser-window-created', (event, window) => {
  if (!window.webContents.isDevToolsOpened()) {
    window.webContents.openDevTools()
    // window.webContents.session.loadExtension(extensions)
    //   .catch((e) => {
    //     console.error('Cannot find the vue extension. Please run "npm run postinstall" to install extension, or remove it and try again!')
    //   })
  }
})